package com.ssyt.ec.exam.servlet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ssyt.ec.common.AppServlet;
import com.ssyt.ec.common.PageModel;
import com.ssyt.ec.common.util.DBUtil;
import com.ssyt.ec.common.util.FastjsonUtil;
import com.ssyt.ec.common.util.SysuserUtil;
import com.ssyt.ec.exam.entity.ExamPaperEntity;
import com.ssyt.ec.exam.service.ExamPaperService;
import com.ssyt.ec.sys.entity.CourseEntity;

@WebServlet("/paper/ExamPaperServlet")
public class ExamPaperServlet extends AppServlet {
	private static final long serialVersionUID = 1L;
	private ExamPaperService paperService = new ExamPaperService();

	public ExamPaperServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		if ("listPaper".equals(command)) {
			listPaper(request, response);
		} else if ("getPaper".equals(command)) {
			getPaper(request, response);
		} else if ("updatePaper".equals(command)) {
			updatePaper(request, response);
		} else if ("addPaper".equals(command)) {
			addPaper(request, response);
		} else if ("deletePaper".equals(command)) {
			deletePaper(request, response);
		} else if ("changeState".equals(command)) {
			changeState(request, response);
		} else if ("listCourse".equals(command)) {
			listCourse(request, response);
		} else if ("search".equals(command)) {
			search(request, response);
		} else if ("preview".equals(command)) {
			preview(request, response);
		} else {
			throw new IllegalStateException("请求非法~");
		}
	}

	/**
	 * 分页查询试卷信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listPaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		PageModel<ExamPaperEntity> paper = paperService.listPaper(sort, order,
				page, rows);
		print(response, FastjsonUtil.toJson(paper));

	}

	private void getPaper(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		ExamPaperEntity paper = paperService.getPaper(id);
		if (paper != null) {
			print(response, FastjsonUtil.toJson(paper));
		}
	}

	/**
	 * 模糊查询试卷信息
	 * 
	 * @param request
	 * @param response
	 */
	private void search(HttpServletRequest request, HttpServletResponse response) {
		String searchName = request.getParameter("searchName");
		String pageStr = request.getParameter("page");
		String rowStr = request.getParameter("rows");
		int page = 0;
		int rows = 0;
		if (pageStr != null && rowStr != null) {
			page = Integer.parseInt(pageStr);
			rows = Integer.parseInt(rowStr);
		}
		String papertypeChoose = request.getParameter("papertype_choose");
		PageModel<ExamPaperEntity> paper = paperService.search(page, rows,
				searchName, papertypeChoose);
		print(response, FastjsonUtil.toJson(paper));
	}

	/**
	 * 试卷信息修改
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		// String papreUrl = request.getParameter("paper_url");
		int paperType = Integer.parseInt(request.getParameter("paper_type"));
		int courseId = Integer.parseInt(request.getParameter("course_id"));
		int totalPoint = Integer.parseInt(request.getParameter("total_point"));
		int passPoint = Integer.parseInt(request.getParameter("pass_point"));
		int totalMinutes = Integer.parseInt(request
				.getParameter("total_minutes"));
		int singleOptionNumber = Integer.parseInt(request
				.getParameter("single_option_number"));
		int singleOptionEachPoint = Integer.parseInt(request
				.getParameter("single_option_each_point"));
		int singleOptionDifficulty = Integer.parseInt(request
				.getParameter("single_option_difficulty"));
		int multiOptionNumber = Integer.parseInt(request
				.getParameter("multi_option_number"));
		int multiOptionEachPoint = Integer.parseInt(request
				.getParameter("multi_option_each_point"));
		int multiOptionDifficulty = Integer.parseInt(request
				.getParameter("multi_option_difficulty"));
		int judgeNumber = Integer
				.parseInt(request.getParameter("judge_number"));
		int judgeEachPoint = Integer.parseInt(request
				.getParameter("judge_each_point"));
		int judgeDifficulty = Integer.parseInt(request
				.getParameter("judge_difficulty"));
		String memo = request.getParameter("memo");
		List<Object> paramList = new ArrayList<>();
		paramList.add(name);
		// paramList.add(papreUrl);
		paramList.add(paperType);
		paramList.add(courseId);
		paramList.add(totalPoint);
		paramList.add(passPoint);
		paramList.add(totalMinutes);
		paramList.add(singleOptionNumber);
		paramList.add(singleOptionEachPoint);
		paramList.add(singleOptionDifficulty);
		paramList.add(multiOptionNumber);
		paramList.add(multiOptionEachPoint);
		paramList.add(multiOptionDifficulty);
		paramList.add(judgeNumber);
		paramList.add(judgeEachPoint);
		paramList.add(judgeDifficulty);
		paramList.add(memo);
		paramList.add(id);
		int row = paperService.updatePaper(paramList);
		if (row == 1) {
			print(response, 1);
		}
	}

	/**
	 * 试卷信息删除
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void deletePaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String ids = request.getParameter("ids");
		int row = DBUtil
				.executeUpdate("DELETE FROM qes_exam_paper WHERE id IN (" + ids
						+ ")");

		if (row >= 1) {
			print(response, 1);
		}
	}

	/**
	 * 试卷状态的修改
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void changeState(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String paperId = request.getParameter("paper_id");
		String paperState = request.getParameter("paper_state");
		paperService.changeState(paperId, paperState);
		response.getWriter().print(paperState);
	}

	private void listCourse(HttpServletRequest request,
			HttpServletResponse response) {
		List<CourseEntity> course = paperService.listCourse();
		print(response, FastjsonUtil.toJson(course));
	}

	/**
	 * 预览
	 * 
	 * @param request
	 * @param response
	 */
	private void preview(HttpServletRequest request,
			HttpServletResponse response) {
		String paperUrl = request.getParameter("paperUrl");
		String examinationJsonStr = null;
		try {
			FileInputStream in = new FileInputStream(paperUrl);
			// size 为字串的长度 ，这里一次性读完
			int size = in.available();
			byte[] buffer = new byte[size];
			in.read(buffer);
			in.close();
			examinationJsonStr = new String(buffer, "UTF-8");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		print(response, JSON.parseObject(examinationJsonStr));
	}

	/**
	 * 试卷新增
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void addPaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
		int operateUserId = SysuserUtil.getUserId(request);
		String name = request.getParameter("name");
		int paperType = Integer.parseInt(request.getParameter("paper_type"));
		int courseId = Integer.parseInt(request.getParameter("course_id"));
		int totalPoint = Integer.parseInt(request.getParameter("total_point"));// 5
		int passPoint = Integer.parseInt(request.getParameter("pass_point"));// 6
		int totalMinutes = Integer.parseInt(request
				.getParameter("total_minutes"));// 7
		int singleOptionNumber = Integer.parseInt(request
				.getParameter("single_option_number"));// 8
//		int singleOptionEachPoint = Integer.parseInt(request.getParameter("single_option_each_point"));// 9
		int singleOptionPoint = Integer.parseInt(request.getParameter("singleOptionPoint"));
		int singleOptionEachPoint = (int) singleOptionPoint / singleOptionNumber;
		int singleOptionDifficulty = Integer.parseInt(request.getParameter("single_option_difficulty"));
		int multiOptionNumber = Integer.parseInt(request.getParameter("multi_option_number"));
		//int multiOptionEachPoint = Integer.parseInt(request.getParameter("multi_option_each_point"));// 12
		int multiOptionPoint = Integer.parseInt(request.getParameter("multiOptionPoint"));
		int multiOptionEachPoint = (int) multiOptionPoint	/ multiOptionNumber;
		int multiOptionDifficulty = Integer.parseInt(request
				.getParameter("multi_option_difficulty"));
		int judgeNumber = Integer
				.parseInt(request.getParameter("judge_number"));
		//int judgeEachPoint = Integer.parseInt(request.getParameter("judge_each_point"));// 15
		int judgePoint = Integer.parseInt(request.getParameter("judgePoint"));
		int judgeEachPoint = (int) judgePoint / judgeNumber;
		int judgeDifficulty = Integer.parseInt(request
				.getParameter("judge_difficulty"));
		String memo = request.getParameter("memo");

		// 操作时间
		Calendar calendar = Calendar.getInstance();
		//获得当前操作时间
		Date date = calendar.getTime();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmsskkkk");
		String dateStr = dateFormat.format(date);
		String fileName = "F:\\ec测试文件\\试卷Json\\" + name + dateStr + ".json";
		// paper_url默认为f:\
		String paperUrl = fileName;
		// 状态默认为1 有效
		int state = 1;
		if (memo == null) {
			memo = "";
		}

		List<Object> paramList = new ArrayList<Object>();
		paramList.add(name); //0
		paramList.add(paperUrl); //1
		paramList.add(paperType); //2
		paramList.add(courseId); //3
		paramList.add(totalPoint); //4
		paramList.add(passPoint); //5
		paramList.add(totalMinutes); //6
		paramList.add(singleOptionNumber); //7
		paramList.add(singleOptionEachPoint); //8
		paramList.add(singleOptionDifficulty); //9
		paramList.add(multiOptionNumber);//10
		paramList.add(multiOptionEachPoint); //11
		paramList.add(multiOptionDifficulty); //12
		paramList.add(judgeNumber);//13
		paramList.add(judgeEachPoint);//14
		paramList.add(judgeDifficulty);//15
		paramList.add(operateUserId);//16
		paramList.add(date);//17
		paramList.add(state);//18
		paramList.add(memo);//19

		int resulet = new ExamPaperService().addPaper(paramList);
		print(response, "{\"resulet\":\"" + resulet + "\"}");
	}

}
